using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using DeathReportManagement.Services;
using DeathReportManagement.Models;

namespace DeathReportManagement.Controllers;

[Authorize]
public class DeathReportController : Controller
{
    private readonly DeathReportService _deathReportService;
    private readonly DictionaryService _dictionaryService;
    private readonly AuthService _authService;
    private readonly ReportSubmissionService _submissionService;
    
    public DeathReportController(
        DeathReportService deathReportService,
        DictionaryService dictionaryService,
        AuthService authService,
        ReportSubmissionService submissionService)
    {
        _deathReportService = deathReportService;
        _dictionaryService = dictionaryService;
        _authService = authService;
        _submissionService = submissionService;
    }
    
    [HttpGet]
    public async Task<IActionResult> Index()
    {
        var reports = await _deathReportService.GetReportsAsync();
        return View(reports);
    }
    
    [HttpGet]
    public async Task<IActionResult> Create()
    {
        await LoadDictionariesAsync();
        return View(new DeathReport());
    }
    
    [HttpPost]
    public async Task<IActionResult> Create(DeathReport report)
    {
        if (!ModelState.IsValid)
        {
            await LoadDictionariesAsync();
            return View(report);
        }
        
        try
        {
            await _deathReportService.CreateAsync(report);
            TempData["Success"] = "死亡报告创建成功";
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
            await LoadDictionariesAsync();
            return View(report);
        }
    }
    
    [HttpGet]
    public async Task<IActionResult> Edit(int id)
    {
        var report = await _deathReportService.GetByIdAsync(id);
        if (report == null)
        {
            return NotFound();
        }
        
        if (_authService.IsDoctor() && report.AuditStatus == AuditStatus.Approved)
        {
            TempData["Error"] = "已审核的报告不能修改";
            return RedirectToAction("Index");
        }
        
        await LoadDictionariesAsync();
        return View(report);
    }
    
    [HttpPost]
    public async Task<IActionResult> Edit(int id, DeathReport report)
    {
        if (!ModelState.IsValid)
        {
            await LoadDictionariesAsync();
            return View(report);
        }
        
        try
        {
            await _deathReportService.UpdateAsync(id, report);
            TempData["Success"] = "死亡报告修改成功";
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
            await LoadDictionariesAsync();
            return View(report);
        }
    }
    
    [HttpGet]
    public async Task<IActionResult> Details(int id)
    {
        var report = await _deathReportService.GetByIdAsync(id);
        if (report == null)
        {
            return NotFound();
        }
        
        return View(report);
    }
    
    [HttpGet]
    public async Task<IActionResult> Print(int id)
    {
        var report = await _deathReportService.GetByIdAsync(id);
        if (report == null)
        {
            return NotFound();
        }
        
        return View(report);
    }
    
    [HttpPost]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> Audit(int id, bool approved)
    {
        try
        {
            await _deathReportService.AuditAsync(id, approved);
            TempData["Success"] = approved ? "审核通过" : "审核退回";
        }
        catch (Exception ex)
        {
            TempData["Error"] = ex.Message;
        }
        
        return RedirectToAction("Details", new { id });
    }
    
    [HttpPost]
    public async Task<IActionResult> SubReport(int id)
    {
        try
        {
            await _deathReportService.SubReportAsync(id, _submissionService);
            TempData["Success"] = "附联上报成功";
        }
        catch (Exception ex)
        {
            TempData["Error"] = ex.Message;
        }
        
        return RedirectToAction("Details", new { id });
    }
    
    [HttpPost]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> MainReport(int id)
    {
        try
        {
            await _deathReportService.MainReportAsync(id, _submissionService);
            TempData["Success"] = "主联上报成功";
        }
        catch (Exception ex)
        {
            TempData["Error"] = ex.Message;
        }
        
        return RedirectToAction("Details", new { id });
    }
    
    private async Task LoadDictionariesAsync()
    {
        ViewBag.Ethnicities = await _dictionaryService.GetByTypeAsync("Ethnicity");
        ViewBag.IdTypes = await _dictionaryService.GetByTypeAsync("IdType");
        ViewBag.MaritalStatuses = await _dictionaryService.GetByTypeAsync("MaritalStatus");
        ViewBag.Educations = await _dictionaryService.GetByTypeAsync("Education");
        ViewBag.PersonalIdentities = await _dictionaryService.GetByTypeAsync("PersonalIdentity");
        ViewBag.DeathLocations = await _dictionaryService.GetByTypeAsync("DeathLocation");
        ViewBag.AddressTypes = await _dictionaryService.GetByTypeAsync("AddressType");
        ViewBag.IntervalUnits = await _dictionaryService.GetByTypeAsync("IntervalUnit");
        ViewBag.HighestDiagnosisUnits = await _dictionaryService.GetByTypeAsync("HighestDiagnosisUnit");
        ViewBag.HighestDiagnosisBases = await _dictionaryService.GetByTypeAsync("HighestDiagnosisBasis");
    }
}